/**
 @Name：layuiAdmin 公共业务
 @Author：贤心
 @Site：http://www.layui.com/admin/
 @License：LPPL
 */
layui.define(['jquery'], function (exports) {
    var $ = layui.$,
        body = layui.$('body'),
        layer = layui.layer,
        table = layui.table,
        xmSelect = layui.xmSelect,
        laydate = layui.laydate,
        form = layui.form,
        upload = layui.upload,
        layedit = layui.layedit;

    // 自动调整card高度 data-free用于控制高度减少余量
    $(function () {
        $('.layui-card-body').each(function (i, e) {
            var free, custom;
            if ($(e).hasClass('full-height')) {
                free = $(e).data('free') ? $(e).data('free') : 40;
                $(e).css('min-height', 400);
                $(e).css('height', $(window).height() - free);
            }

            if ($(e).hasClass('half-height')) {
                free = $(e).data('free') ? $(e).data('free') : 40;
                $(e).css('height', ($(window).height() / 2) - free)
            }

            if ($(e).hasClass('custom-height')) {
                free = $(e).data('free') ? $(e).data('free') : 40;
                custom = $(e).data('custom') ? $(e).data('custom') : 40;
                $(e).css('height', ($(window).height() * (custom / 100)) - free)
            }
        })
    })

    // 选项卡的自适应高度
    $('.layui-tab').each(function (i, e) {
        var free;
        if ($(e).hasClass('full-height')) {
            free = $(e).data('free') ? $(e).data('free') : 0;
            $(e).css('height', $(e).parent().height() - free)
            $(e).find('.layui-tab-content').height($(e).height() - $(e).find('.layui-tab-title').height() - 18);
        }
    })

    // 自适应table高度，改过layui.all.js 新增了个customHeight
    $('.layui-table-view').each(function (i, e) {
        if ($(e)[0].dataset.customheight) {     // data方法获取不到只能取属性
            var height = $(e).outerHeight();
            var toolHeight = $(e).find('.layui-table-tool').outerHeight();
            var pageHeight = $(e).find('.layui-table-page').outerHeight();
            var headerHeight = $(e).find('.layui-table-header').outerHeight();
            $(e).find('.layui-table-main').height(height - (pageHeight ? pageHeight : 0) - (toolHeight ? toolHeight : 0) - headerHeight)
        }
    })

    // 关闭弹窗
    body.on('click', '.close-btn,.layerClose', function () {
        layerClose($(this));
    })

    // 通用关闭弹窗
    function layerClose(_elm) {
        var frameElm = $(_elm).parents('.layui-layer-page');
        if (frameElm.length > 0) {
            index = frameElm.attr('times');
            layer.close(index);
        } else {
            parent.layer.close(parent.layer.index);
        }
    }

    //手机端表单搜索栏隐藏显示按钮逻辑
    $('body').on('click', '.toolbar-search-show', function () {
        $(this).parents('form').find('.toolbar-search-area').toggleClass('layui-hide-xs');
    })

    // 基础表单搜索
    $.fn.tableSearch = function (element) {
        var form = $(this);
        table.reload(form.attr('for-table-filter'), {
            method: 'post',
            where: {
                searchData: JSON.stringify(form.serializeArray()),
                _csrf: $('meta[name="csrf-token"]').attr("content")
            },
            page: table.thisTable.config[form.attr('for-table-filter')].page ? {
                curr: 1
            } : false,
            parseData: function (res) { //res 即为原始返回的数据
                if (typeof customParseData === 'function') {
                    return customParseData(res)
                }
            },
            done: function (res, curr, count) {
                if (typeof afterSearch === 'function') {
                    afterSearch(res, curr, count)
                }
            }
        });
    }

    //表单搜索
    body.on('click', '.toolbar-search-btn', function () {
        var _this = $(this);
        var toolbar_form = _this.parents("form");
        var for_table_filter = toolbar_form.attr('for-table-filter');
        if (!for_table_filter) {
            return false;
        }

        toolbar_form.tableSearch();
    })

    //表单搜索条件重置
    body.on('click', '.toolbar-search-reset', function () {
        var _this = $(this);
        var toolbar_form = _this.parents("form");
        var for_table_filter = toolbar_form.attr('for-table-filter');
        if (!for_table_filter) {
            return false;
        }
        toolbar_form[0].reset();
        toolbar_form.tableSearch();
        if (toolbar_form.find('.xm-tree').length > 0) {
            $.each(xmSelect.get(toolbar_form.find('.xm-tree')), function (xi, xe) {
                xe.setValue([''])
            })
        }
    })

    /**
     * 表单excel导出按钮，自动获取按钮外级的 form 的所有值为搜索值
     * class='export-excel' 必填
     * data-url='?' 必填 表单提交的URL
     */
    body.on('click', '.export-excel', function () {
        var _this = $(this);
        var form = _this.parents('form');
        var searchData = JSON.stringify(form.serializeArray());

        if (form.find('.searchData').length) {
            form.find('.searchData').val(searchData)
        } else {
            form.append("<input type='hidden' name='searchData' class='searchData' value='" + searchData + "' />")
        }

        $(form).attr({
            'action': _this.data('url'),
            'target': '_blank',
            'method': 'post'
        }).submit();

        form.find('.searchData').remove();
    })

    /**
     * 时间选择框自加载
     * class="auto-date" 必填
     * date-type="year|month|date|datatime..."
     */
    $('.auto-date').each(function () {
        var date_type = $(this).attr('date-type');
        //组件时间格式
        if (!date_type) {
            date_type = 'date';
        }

        laydate.render({
            elem: this,
            type: date_type,
            trigger: 'click'
        });
    })

    /**
     * 上传组件自动加载
     * 需绑定到按钮上，class="upload-file-btn"，data-name="?"
     * 如果存在data-id="?",data-module="?"则执行搜索并遍历显示
     */
    $('.upload-file-btn').each(function () {
        var that = $(this);
        var name = $(this).data('name') ? $(this).data('name') : 'attachment'; //上传后生成的input的name[]
        var data_id = $(this).data('id'); //data-id和data-module都存在则检索并遍历显示已经上传的组件
        var module = $(this).data('module');

        //如果两个值都不为空则加载文件列表
        if (data_id && module) {
            that.before("<span class='loading-status'><i class='layui-anim layui-anim-rotate layui-anim-loop layui-icon layui-icon-loading'></i> 附件加载中...</span>");
            $.ajax({
                type: "GET",
                url: "/index.php?r=common/file/file-list&module=" + module + "&data_id=" + data_id,
                success: function (res) {
                    that.prev('.loading-status').remove();
                    if (res.data.length != 0) {
                        $.each(res.data, function (index, d) {
                            var html = '<div class="upload-file-item" style="margin-bottom: 5px">\n' +
                                '                            <div class="layui-inline">\n' +
                                '                                <a target="_blank" style="color:#01AAED" href="' + d.url + '">' + d.title + '</a>\n' +
                                '                            </div>\n' +
                                '                            <div class="layui-inline" style="padding-top: 4px;padding-left: 10px">\n' +
                                '                                <a href="' + d.url + '" download="'+d.title+'" title="下载附件"><i class="layui-icon layui-icon-download-circle"></i></a>\n' +
                                '                                <a href="javascript:void(0)" class="upload-file-remove-btn" data-id="' + d.id + '" data-name="' + name + '">\n' +
                                '                                    <i class="layui-icon layui-icon-delete"></i>\n' +
                                '                                </a>\n' +
                                '                            </div>\n' +
                                '                        </div>';
                            that.before(html);
                        })
                    }
                }
            });
        }

        upload.render({
            elem: this,
            accept: 'file',
            url: "/index.php?r=/common/file/upload",
            before: function (obj) {
                obj.preview(function (index, file, result) {
                    file_name = file.name;
                })
            },
            done: function (res, index) {
                var html = '<div class="upload-file-item" style="margin-bottom: 5px">\n' +
                    '                            <div class="layui-inline">\n' +
                    '                                <input type="hidden" class="layui-input" value="' + res.data.src + '" name="' + name + '[' + index + '][url]">\n' +
                    '                                <input type="text" class="layui-input" lay-verify="required" placeholder="请输入文件名" value="' + file_name + '" name="' + name + '[' + index + '][title]">\n' +
                    '                            </div>\n' +
                    '                            <div class="layui-inline">\n' +
                    '                                <a href="javascript:void(0)" class="upload-file-remove-btn">\n' +
                    '                                    <i class="layui-icon layui-icon-delete"></i>\n' +
                    '                                </a>\n' +
                    '                            </div>\n' +
                    '                        </div>';
                that.before(html);
            }
        });
    })

    /**
     * 上传组件删除已经上传的文件
     * 如果存在data-id=？则在当前<form>下添加attachment_remove[]的input
     */
    $('body').on('click', '.upload-file-remove-btn', function () {
        var id = $(this).data('id');
        var name = $(this).data('name');
        if (id) {
            $(this).parents('form').append("<input type='hidden' name='" + name + "_remove[]' value='" + id + "'>");
        }

        $(this).parents('.upload-file-item').remove();
    })

    /**
     * layer (iframe弹窗)
     * class="iframe-layer" 必填
     * data-url="url" 必填 弹框iframe的url
     * data-title="title" 选填 弹框的标题 default="信息"
     * data-size="width,height" 选填 弹框的大小 default="['80%', '80%']" 支持css大小识别符
     * data-reload="table" 选填 关闭后刷新上级table 此字段为数据表格的lay-filter="table"的值，用于绑定要刷新的数据表格
     */
    body.on('click', '.iframe-layer', function () {
        var _this = $(this);
        if (_this.hasClass('layui-btn-disabled')) {
            return false;
        }

        // 可自定义弹窗前置操作
        if (_this.data('before') && typeof layerBefore === "function") {
            if (!layerBefore()) {
                return false;
            }
        }

        var before_callback = _this.attr('before-callback');
        if (before_callback) {
            if (!eval(before_callback + '(_this)')) {
                return false;
            }
        }

        var url = _this.data('url') ? _this.data('url') : ''; //url
        var title = _this.data('title') ? _this.data('title') : '信息'; //标题
        var size = _this.data('size') ? _this.data('size').split(',') : ['98%', '98%']; //弹框大小 宽,高
        var reload = _this.data('reload');
        var jump = _this.data('jump');

        layer.open({
            type: 2,
            title: title,
            area: size,
            content: url,
            maxmin: true,
            shade: 0.3,
            shadeClose: false,
            success: function (layero, index) {
                switch (_this.data('type')) {
                    case 'chooseUser':
                        var field = _this.data('field') ? _this.data('field') : 'user';
                        var body = layer.getChildFrame('body', index);
                        $(body).find('.field').val(field);
                        $(body).find('.call').val(_this.data('call') ? 1 : 0);
                        break;
                }
            },
            end: function () {
                if (reload) {
                    table.reload(reload);
                }

                if (jump) {
                    window.location.reload();
                }
            }
        })
    })

    /**
     * layer (confirm弹窗)
     * class="confirm-layer" 必填
     * data-url="url" 必填 弹框success后请求的ajax的url
     * data-title="title" 选填
     * data-content="content" 选填
     * data-icon="2" 选填 弹窗图标 1对号 2叉号 3问号 4锁 5不开心 6开心 7叹号
     * data-reload="table" 选填 请求ajax返回成功参数后要刷新的table的lay-filter
     * success-callback="functionName(this,res)" 选填 请求ajax返回成功参数后回调方法
     * data-method="post" 选填 请求所用的方法 default="post"
     */
    body.on('click', '.confirm-layer', function () {
        var _this = $(this);

        var url = _this.data('url') ? _this.data('url') : ''; //url
        var method = _this.data('method') ? _this.data('method') : 'post';
        var title = _this.data('title') ? _this.data('title') : '提示'; //标题
        var content = _this.data('content') ? _this.data('content') : '确定要删除此数据吗？'; //提示内容
        var icon = _this.data('icon') ? _this.data('icon') : 2; //图标，1对号 2叉号 3问号 4锁 5不开心 6开心 7叹号
        var reload = _this.data('reload');
        var success_callback = _this.attr('success-callback');


        layer.confirm(content, {icon: icon, title: title}, function (index) {
            layer.close(index);
            var load_index = layer.load(2, {
                shade: [0.3, '#000000']
            });

            $.ajax({
                type: method,
                data: {_csrf: $('meta[name="csrf-token"]').attr("content")},
                url: url,
                success: function (res) {
                    layer.close(load_index);
                    if (res.msg) {
                        layer.msg(res.msg);
                    }

                    if (res.error == 0) { //成功
                        if (reload) {
                            table.reload(reload);
                        }

                        if (success_callback) {
                            window[success_callback](_this, res);
                        }
                    }
                }
            });
        });
    })

    /**
     * dialog弹窗
     * before-callback="functionName" 选填 页面渲染成功后后回调方法
     * end-callback="functionName" 选填 页面销毁后后回调方法
     */
    body.on('click', '.dialog-layer', function () {
        var _this = $(this);
        if (_this.hasClass('layui-btn-disabled')) {
            return false;
        }
        var html = _this.data('html-elem') ? _this.data('html-elem') : ''; //html所容器的elem
        var title = _this.data('title') ? _this.data('title') : '信息'; //标题
        var size = _this.data('size') ? _this.data('size').split(',') : ['98%', '98%']; //弹框大小 宽,高
        var reload = _this.data('reload');
        var before_callback = _this.attr('before-callback');
        var end_callback = _this.attr('end-callback');

        // 可自定义弹窗前置操作
        if (_this.data('before') && typeof layerBefore === "function") {
            if (!layerBefore()) {
                return false;
            }
        }
        layer.open({
            type: 1,
            title: title,
            area: size,
            content: $(html).html(),
            maxmin: true,
            shade: 0.3,
            shadeClose: false,
            success: function (layero, index) {
                if (before_callback) {
                    window[before_callback](_this);
                }
            },
            end: function () {
                if (reload) {
                    table.reload(reload);
                }

                if (end_callback) {
                    window[end_callback](_this);
                }
            }
        })
    })

    /**
     * form表单ajax提交
     * class="ajax-submit" 必填 在正常的form提交按钮上加class
     * after-success="none|jump|close" 选填 ajax返回成功后进行的事件
     * none不进行任何操作停留在本页|jump当前页进行跳转，后端返回了data.url则跳转到此页面，否则刷新|close关闭当前layer，并触发end()事件，如果layer有reload则刷新table
     */
    body.on('click', '.ajax-submit', function () {
        var _this = $(this),
            filter = $(this).attr('lay-filter'),
            after_success = $(this).attr('after-success'),
            _type = $(this).data('type'),
            _for = $(this).data('for'),
            before_submit_callback = $(this).attr('before-submit-callback');

        //阻止按钮点击事件
        if (_this.attr('disabled')) {
            return false;
        }

        // 提交前置操作
        if (_this.data('before') && typeof submitBefore === "function") {
            if (!submitBefore(_this)) {
                return false;
            }
        }

        form.on('submit(' + filter + ')', function (data) {
            var url = data.form.action;
            var method = data.form.method;

            if (before_submit_callback) {
                if (!window[before_submit_callback](data, _this)) {
                    return false;
                }
            }

            if (!_this.data('search')) {
                _this.addClass('layui-btn-disabled');
                _this.attr('disabled', 'disabled');
            }
            data.field._csrf = $('meta[name="csrf-token"]').attr("content");
            $.ajax({
                type: method,
                url: url,
                data: data.field,
                success: function (res) {
                    if (res.msg) {
                        layer.msg(res.msg);
                    }
                    if (res.error == 0) { //成功
                        setTimeout(function () {
                            switch (after_success) {
                                case 'close':
                                    layerClose(_this);
                                    break;
                                case 'none':
                                    return true;
                                case 'refresh':
                                    layerClose(_this);
                                    if (_type && _for) {
                                        eval('layui.' + _type).reload(_for);
                                    } else {
                                        window.location.reload();
                                    }
                                    break;
                                case 'call':
                                    submitCall(res);
                                    break;
                                default:
                                    var url = res.data.url;
                                    console.log(url);
                                    if (url) { //后端传过来了url则重定向 否则刷新
                                        window.location.href = url;
                                    } else {
                                        window.location.reload();
                                    }
                                    break;
                            }
                        }, 200);
                    } else { //失败
                        _this.removeClass('layui-btn-disabled');
                        _this.removeAttr('disabled');
                    }
                }
            });
            return false;
        });
    })

    /**
     * 元素抖动动画
     * @param intShakes 抖动测试
     * @param intDistance 抖动幅度
     * @param intDuration 抖动时长
     * @returns
     */
    $.fn.shake = function (intShakes /*Amount of shakes*/, intDistance /*Shake distance*/, intDuration /*Time duration*/) {
        this.each(function () {
            var jqNode = $(this);
            jqNode.css({position: 'relative'});
            for (var x = 1; x <= intShakes; x++) {
                jqNode.animate({
                    left: (intDistance * -1),
                    bottom: (intDistance * -1)
                }, (((intDuration / intShakes) / 4)))
                    .animate({left: intDistance, bottom: intDistance}, ((intDuration / intShakes) / 2))
                    .animate({left: 0, bottom: 0}, (((intDuration / intShakes) / 4)));
            }
        });
        return this;
    }

    //监听F5刷新阻止冒泡
    document.addEventListener("keydown", function (e) {
        e = e || window.event;
        if ((e.which || e.keyCode) == 116) {
            window.location.reload();
            if (e.preventDefault) {
                e.preventDefault();
            } else {
                event.keyCode = 0;
                e.returnValue = false;
            }
        }
    }, false);

    //对外暴露的接口
    exports('common', {});
});